﻿using System;
using Microsoft.Win32;

class Registry_Add_CurrentUser
{
    // 在当前用户下注册右键菜单（背景/目录）
    // HKCU\Software\Classes\Directory\Background\shell
    // HKCU\Software\Classes\Directory\shell
    
    // HKCR\Directory\shell
    // HKCR\Directory\Background\shell 
    
    
    public static int AddAppShellKeys(string appName)
    {
        string[] paths =
        {
            $@"Directory\Background\shell\{appName}",
            $@"Directory\shell\{appName}"
        };
        return Add_User_Classes_Keys(appName, paths);
    }

    private static int Add_User_Classes_Keys(string appName, params string[] paths)
    {
        int addedCount = 0;

        foreach (var path in paths)
        {
            try
            {
                string parentPath = System.IO.Path.GetDirectoryName(path);
                string subKeyName = System.IO.Path.GetFileName(path);

                // 修改为当前用户 HKCU\Software\Classes
                using (RegistryKey baseKey = Registry.CurrentUser.OpenSubKey("Software\\Classes", writable: true))
                {
                    if (baseKey == null)
                    {
                        Console.WriteLine("无法打开 HKCU\\Software\\Classes");
                        continue;
                    }

                    using (RegistryKey parentKey = baseKey.CreateSubKey(parentPath))
                    {
                        if (parentKey == null)
                        {
                            Console.WriteLine($"创建父键失败: {parentPath}");
                            continue;
                        }

                        using (RegistryKey targetKey = parentKey.CreateSubKey(subKeyName))
                        {
                            if (targetKey == null)
                            {
                                Console.WriteLine($"创建子键失败: {path}");
                            }
                            else
                            {
                                // 设置右键菜单显示名称
                                targetKey.SetValue("", $"open with {appName}");

                                // 设置默认命令，比如打开记事本
                                using (RegistryKey commandKey = targetKey.CreateSubKey("command"))
                                {
                                    commandKey.SetValue("", @"notepad.exe");
                                }

                                Console.WriteLine($"已添加注册表项: {path}");
                                addedCount++;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加 {path} 失败: {ex.Message}");
            }
        }

        return addedCount;
    }
}

class Add_Current_User
{
    public static void Run(string appName)
    {
        int result = Registry_Add_CurrentUser.AddAppShellKeys(appName);

        Console.WriteLine($"注册完成，共添加 {result} 个注册表项（仅当前用户）。");
    }
}
